<template>
  <div class="model-list-container" v-loading="loading">
    <BasicTable
      @register="registerTable"
      :rowSelection="{ type: 'checkbox', onChange: onSelectChange }"
      @change="isDisable = true"
    >
      <template #tableTitle>
        <a-button @click="handleCreate" type="primary"> 新增 </a-button>
        <!-- <a-button class="ml-2" type="info" @click="handleImport()"> 导入 </a-button> -->
        <!-- <a-button class="ml-2" type="info" @click="handleExport"> 导出 </a-button> -->
        <!-- <a-button :disabled="isDisable" class="ml-2" type="info" @click="handleExportSQL2">
          导入
        </a-button> -->

        <ButtomImport @register="rgImport" @beforeUpload="handleImportJson" />

        <Popover
          class="ml-2"
          placement="bottom"
          trigger="click"
          :destroyTooltipOnHide="true"
          v-model:visible="visible"
        >
          <template #content>
            <div style="display: flex; align-items: center">
              <Select
                style="width: 160px"
                :options="options"
                allow-clear
                :show-search="true"
                :disabled="loading"
                :filter-option="handleFilterOption"
                v-model:value="dataSourceItem"
                :field-names="{ label: 'connName', value: 'connCode' }"
              />

              <a-button
                type="primary"
                class="ml-4"
                @click="handleSynchronization"
                :loading="loading"
                :disabled="!dataSourceItem"
                >同步</a-button
              >
            </div>
          </template>
          <a-button type="primary">同步源数据表</a-button>
        </Popover>
        <a-button :disabled="isDisable" class="ml-2" type="primary" @click="handleExportSQL">
          导出SQL
        </a-button>
      </template>

      <!-- <template #slotP="data">
        <Checkbox />
        <div>123123</div>{{ data }}
      </template> -->
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '编辑',
                onClick: handleEdit.bind(null, record),
              },
              // {
              //   label: '导入',
              //   onClick: handleImport.bind(null, record.modelCode),
              // },
              {
                label: '导出',
                onClick: handleExport.bind(null, record),
              },
              {
                label: '获取SQL',
                onClick: handleExportSQL.bind(null, record),
              },

              {
                label: '删除',
                deleteDialogType: true,
                showModalConfirm: {
                  title: h(
                    'span',
                    {
                      style: {
                        fontWeight: 'bold',
                      },
                    },
                    '删除提示',
                  ),
                  icon: h(ExclamationCircleFilled),
                  content: '确认删除定义表和数据库表吗？',
                  okText: '确定',
                  cancelText: '取消',
                  maskClosable: false,

                  onOk: handleDelete.bind(null, record),
                },
              },
              // {
              //   label: '导出SQL',
              //   onClick: handleExportSQL.bind(null, record),
              // },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <!-- <ModelDesignDrawer :classify="1" @register="registerDrawer" @success="handleSuccess" /> -->
    <MenuDrawer @register="registerDrawer" @success="handleSuccess" />
    <ExportSQL @register="registerModal" @success="handleSuccess" />
    <ExportSQL2 @register="registerModal2" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  import { Popover, Select } from 'ant-design-vue';
  import { ExclamationCircleFilled } from '@ant-design/icons-vue';

  import { getMetaSqlApi } from '/@/api/database/metadata';
  import { defineComponent, ref, h } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { ButtomImport, useButtomImport } from '/@/components/ImportButton';
  import { downloadByData } from '/@/utils/file/download';
  import { useMessage } from '/@/hooks/web/useMessage';
  // import { useGo } from '/@/hooks/web/usePage';
  import MenuDrawer from './MenuDrawer.vue';
  import ExportSQL from './ExportSQL.vue';
  import ExportSQL2 from './ExportSQL2.vue';
  import { importModelApi, MODEL_TYPE } from '/@/api/config-center/model-design';
  import { getMetaPageApi, delMetaApi, getMetaModelInfoApi } from '/@/api/database/metadata';
  import { columns } from './design.data';
  import { searchFormSchema } from './menu.data';
  import { useDrawer } from '/@/components/Drawer';
  import { getDBListApi, syncDataBase } from '/@/api/database/account';
  import { DICT } from '/@/enums/dict';
  // import ModelDesignDrawer from '../model-design/index.vue';
  import { useModal } from '/@/components/Modal';
  export default defineComponent({
    name: 'ModelList',
    components: {
      ExportSQL,
      ExportSQL2,
      BasicTable,
      TableAction,
      ButtomImport,
      MenuDrawer,
      Popover,
      Select,
    },
    setup() {
      const isDisable = ref<boolean>(true);
      const loading = ref(false);
      const options = ref<any[]>([]);
      const dataSourceItem = ref<string>('');
      const visible = ref<boolean>(false);

      const { createMessage } = useMessage();
      // const go = useGo();

      const [registerTable, { reload, getSelectRows }] = useTable({
        // api: getModelByListApi,
        api: getMetaPageApi,
        columns,
        formConfig: {
          labelWidth: 120,
          schemas: searchFormSchema,
          submitFunc: async () => {
            isDisable.value = true;
            reload();
          },
          resetFunc: async () => {
            isDisable.value = true;
          },
        },

        useSearchForm: true,
        showTableSetting: false,
        bordered: false,
        showIndexColumn: true,
        // rowSelection: {
        //   type: 'checkbox',
        // },
        actionColumn: {
          width: 200,
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
        },
      });
      function onSelectChange() {
        let res = getSelectRows();

        isDisable.value = !res[0]?.tableId;
      }
      const [registerDrawer, { openDrawer }] = useDrawer();
      const [rgImport, { importFile }] = useButtomImport();
      const [registerModal, { openModal }] = useModal();
      const [registerModal2, { openModal: openModal2 }] = useModal();
      function handleCreate(record: Recordable) {
        console.log('点击新增：', record);
        // go('/config-center/model-form/index');

        openDrawer(true, {
          isUpdate: false,
          record,
          // openDrawer: {},
        });
      }

      async function getDataSourceList() {
        options.value = await getDBListApi({ type: DICT.COMPONENT_NAME });
      }
      getDataSourceList();

      function handleEdit(record: Recordable) {
        // go({
        //   path: '/config-center/model-form/index',
        //   query: {
        //     id: record.modelId,
        //   },
        // });

        openDrawer(true, {
          record,
          isUpdate: true,
          // isUpdate: false,
        });
      }

      async function handleDelete(record: Recordable) {
        await delMetaApi(record.tableId);
        reload();
        // const tableList = getRolesDataSource();
        // const index = tableList.findIndex((item) => item.tableId === record.tableId);
        // tableList.splice(index, 1);
        createMessage.success('操作成功');
      }

      function handleSuccess() {
        reload();
      }
      let currModelCode = '';

      async function handleImport(modelCode = '') {
        currModelCode = modelCode;
        console.log('导入1：', modelCode);
        // return;
        await importFile();
      }

      async function handleImportJson(jsonStr) {
        console.log('导入2：', jsonStr);
        const editorJsonData = JSON.parse(jsonStr);
        if (editorJsonData.classify !== MODEL_TYPE.LIST)
          return createMessage.warn('导入失败，请使用列表模型的数据格式');
        if (currModelCode) {
          editorJsonData.modelCode = currModelCode;
        }
        await importModelApi(editorJsonData);
        createMessage.success('导入成功');
        reload();
      }
      async function getSQL(params) {
        try {
          let str = '';
          // dataBase.value = '';
          params.forEach((e) => {
            str = e + ',' + str;
          });
          str = str.slice(0, -1);
          console.log('str:', str);
          let data = await getMetaSqlApi(str);
          console.log('data:', data);
          data ? '' : createMessage.warn('表定义与实际库定义一致！');
          return data;
          // await getMetaExecuteSqlApi(dataBaseInfo.value);
          // createMessage.success('执行成功');
        } catch (error) {
          return null;
        }
        // closeModal();
      }
      async function handleExportSQL2(record, e) {
        let iDs: any = [];
        if (record && record.tableId) {
          iDs.push(record.tableId);
          e.stopPropagation();
          let res = await getSQL(iDs);
          console.log('res1111:', res);
          if (res === 'null' || res === null) {
            console.log('res2222:', res);
            return;
          }
        } else {
          let res = getSelectRows();
          res.forEach((e) => {
            iDs.push(e.tableId);
          });
        }

        openModal2(true, {
          iDs,
          isUpdate: !!(record && record.tableId),
        });
        // const data = await getMetaModelInfoApi({ tableType, tableCode, tableName });
        // downloadByData(data, `${tableName || 'all'}_${Date.now()}.xlsx`);
      }
      async function handleExportSQL(record, e) {
        let iDs: any = [];
        if (record && record.tableId) {
          iDs.push(record.tableId);
          e.stopPropagation();
          let res = await getSQL(iDs);
          console.log('res1111:', res);
          if (res === 'null' || res === null) {
            console.log('res2222:', res);
            return;
          }
        } else {
          let res = getSelectRows();
          res.forEach((e) => {
            iDs.push(e.tableId);
          });
        }

        openModal(true, {
          iDs,
          isUpdate: !!(record && record.tableId),
        });
        // const data = await getMetaModelInfoApi({ tableType, tableCode, tableName });
        // downloadByData(data, `${tableName || 'all'}_${Date.now()}.xlsx`);
      }
      async function handleExport({ tableType, tableCode, tableName }) {
        console.log('导出：', tableType);
        const data = await getMetaModelInfoApi({ tableType, tableCode, tableName });
        downloadByData(data, `${tableName || 'all'}_${Date.now()}.xlsx`);
      }

      async function handleSynchronization() {
        loading.value = true;
        try {
          await syncDataBase(dataSourceItem.value);
          createMessage.success('同步成功');
          dataSourceItem.value = '';
          visible.value = false;
          reload();
        } finally {
          loading.value = false;
        }
      }

      function handleFilterOption(val, option) {
        return option.connName.indexOf(val) > -1;
      }

      return {
        registerTable,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleImport,
        handleExportSQL2,
        handleExportSQL,
        handleExport,
        registerDrawer,
        rgImport,
        handleImportJson,
        onSelectChange,
        registerModal2,
        registerModal,
        isDisable,
        options,
        dataSourceItem,
        handleSynchronization,
        visible,
        handleFilterOption,
        loading,
        ExclamationCircleFilled,
        h,
      };
    },
  });
</script>
